﻿namespace Core
{
    public class ItemSlot
    {
        public ItemContainer container { get; private set; }
        public int index { get; private set; }
        public int instanceId { get; private set; }
        public int itemId { get; private set; }
        public int count { get; private set; }

        public bool IsEmpty => count == 0;

        public ItemSlot(ItemContainer itemContainer, int index)
        {
            container = itemContainer;
            this.index = index;
        }

        public void UpdateCount(int change)
        {
            count += change;
            if (count <= 0)
            {
                count = 0;
                UpdateItemByInstId(this.instanceId, this.itemId, 0);
            }
            else
            {
                OnItemChanged(this.itemId);
            }
        }

        public void UpdateItem(int itemId, int count)
        {
            UpdateItemByInstId(this.instanceId, itemId, count);
        }

        public void UpdateItemByInstId(int instanceId, int itemId, int count)
        {
            var oldItem = this.itemId;
            this.instanceId = instanceId;
            this.itemId = itemId;   
            this.count = count;

            if(itemId == 0 || count <= 0)
            {
                Reset();
            }
            OnItemChanged(oldItem);
        }

        public void Clear()
        {
            UpdateItemByInstId(this.instanceId, this.itemId, 0);
        }

        public void Reset()
        {
            this.instanceId = 0;
            this.itemId = 0;
            this.count = 0;
        }

        private void OnItemChanged(int oldItemId)
        {
            World.GetComponent<EventComponent>().Publish(new ItemChange 
            {
                container = container,
                newItemId = this.itemId,
                oldItemId = oldItemId,
                slot = this
            });
        }
    }
}
